#include <semaphore.h>
#include <pthread.h>
#include <time.h> 

#define MAX_LEN 10
#define MAX_PRODUCE_CNT 20

int queue[MAX_LEN];
int write = 0, read = 0;
sem_t consume, produce;

void *consumer_run(void *arg) {
    int idx;

    for(;;) {
        sem_wait(&produce);
        idx = queue[read % MAX_LEN];
        read += 1;
        sem_post(&consume);
        printf("Consumer consume product %d.\n", idx);
        usleep(1000);
    }
}

void *producer_run(void *arg) {
    int idx;

    for(idx = 0; idx < MAX_PRODUCE_CNT; ++idx) {
        sem_wait(&consume);
        queue[write % MAX_LEN] = idx;
        write += 1;
        printf("Producer produce product %d.\n", idx);
        sem_post(&produce);
        usleep(1000);
    }
}

int main(int argc, char *argv[]) {
    sem_init(&consume, 0, MAX_LEN);
    sem_init(&produce, 0, 0);

    pthread_t consumer, producer;

    pthread_create(&consumer, NULL, consumer_run, NULL);
    pthread_create(&producer, NULL, producer_run, NULL);

    pthread_join(consumer, NULL);
    pthread_join(producer, NULL);

    return 0;
}